package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;

/**
 * 核心配置类: 用来替换xml配置文件
 */
//开启组件扫描
@ComponentScan("com.itheima")
//加载外部资源配置文件
@PropertySource("jdbc.properties")
//加载子配置类
@Import({MapperConfig.class})
//声明当前配置类为核心配置类
@Configuration
public class SpringConfig {

    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    //声明一个方法获取数据源对象
    @Bean
    public DataSource getDataSource(){
        //1. 创建数据库连接池对象
        DruidDataSource source = new DruidDataSource();
        //2. 配置连接数据库的四大基本特征
        source.setDriverClassName(driverClassName);
        source.setUrl(url);
        source.setUsername(username);
        source.setPassword(password);
        return source;
    }

    //声明一个方法获取SqlSessionFactoryBean对象
    @Bean
    public SqlSessionFactoryBean getSqlSessionBean(DataSource dataSource){
        //1. 创建一个SqlSessionFactoryBean对象
        SqlSessionFactoryBean sb = new SqlSessionFactoryBean();
        //2. 注入数据源
        sb.setDataSource(dataSource);
        //3. 设置类型别名
        sb.setTypeAliasesPackage("com.itheima.pojo");
        return sb;
    }
}
